import React, { useRef, useState, useEffect } from 'react';
import { NavBar, List } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Toast } from 'antd-mobile';
import SliderCaptcha from 'rc-slider-captcha';
import {QRCodeSVG} from 'qrcode.react'// 引入QRCode组件用于生成二维码
import * as faceapi from 'face-api.js';
import styles from './Renlian.module.css';
import  {http,host,port} from '../utils/host'

function Renlian() {
    const navigate = useNavigate();
    const fileInputRef = useRef();
    const [userAvatar, setUserAvatar] = useState(localStorage.getItem("userAvatar") || "");
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const username = userInfo.username || localStorage.getItem("username") || "";
    const back = () => {
        navigate(-1);
    }
    const user = JSON.parse(localStorage.getItem('user'));

    let video = useRef();
    let canvas = useRef();
    const [showQRModal, setShowQRModal] = useState(false); // 控制二维码弹窗显示
    const [showModal, setShowModal] = useState(false);
    const [loading, setLoading] = useState(false);
    const [success, setSuccess] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    const [step, setStep] = useState(0); // 0:眨眼 1:张嘴 2:摇头 3:自动识别
    const [bgFlash, setBgFlash] = useState(false);
    const [modelsLoaded, setModelsLoaded] = useState(false);
    const baseEAR = useRef(null);
    const [flashColor, setFlashColor] = useState('#ffe066');
    const flashColors = ['#ffe066', '#ff6666', '#66ccff', '#99ff99']; // 可自定义多种颜色
    const flashInterval = useRef(null);
    const blinkCount = useRef(0);
    const baseEARArr = useRef([]);
    const [realName, setRealName] = useState('');
    // 新增邮箱弹框相关 state
    const [showEmailModal, setShowEmailModal] = useState(false);
    const [inputEmail, setInputEmail] = useState('');
    const [emailError, setEmailError] = useState('');
    // 新增滑块和验证码相关 state
    const [showSlider, setShowSlider] = useState(false);
    const [showCodeModal, setShowCodeModal] = useState(false);
    const [inputCode, setInputCode] = useState('');
    const [codeError, setCodeError] = useState('');
    const [email, setEmail] = useState(localStorage.getItem('userEmail') || (user?.email || ''));
    const [qianming, setQianming] = useState(''); // 个性签名

    // 加载 face-api.js 模型
    useEffect(() => {
        Promise.all([
            faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
            faceapi.nets.faceLandmark68Net.loadFromUri('/models')
        ]).then(() => setModelsLoaded(true));
    }, []);

    useEffect(() => {
        if (showModal && modelsLoaded) {
            open();
            setErrorMsg('');
            setLoading(false);
            setSuccess(false);
            setStep(0);
            // 重置检测相关数据
            baseEAR.current = null;
            baseEARArr.current = [];
            blinkCount.current = 0;
            setTimeout(() => {
                detectStep(0);
            }, 1000);
        } else if (!showModal) {
            close();
            setLoading(false);
            setSuccess(false);
            setErrorMsg('');
            setStep(0);
            setBgFlash(false);
            // 重置检测相关数据
            baseEAR.current = null;
            baseEARArr.current = [];
            blinkCount.current = 0;
        }
        // eslint-disable-next-line
    }, [showModal, modelsLoaded]);

    useEffect(() => {
        const storedName = localStorage.getItem('realName');
        if (storedName) setRealName(storedName);
        // 从本地存储获取个性签名
        const qianming = localStorage.getItem('userQianming') || '';
        setQianming(qianming);
    }, []);

    // 步骤检测
    const detectStep = async (currentStep) => {
        if (!video.current) return;
        
        // 每个步骤所需的颜色
        setFlashColor(flashColors[currentStep % flashColors.length]);
        
        // 根据不同步骤执行不同的检测
        switch (currentStep) {
            case 0: // 眨眼检测
                setErrorMsg('请看着屏幕并眨眨眼...');
                setBgFlash(true);
                detectBlink();
                break;
            case 1: // 张嘴检测
                setErrorMsg('请缓慢张嘴...');
                setBgFlash(true);
                detectMouth();
                break;
            case 2: // 摇头检测
                setErrorMsg('请缓慢左右摇头...');
                setBgFlash(true);
                detectHeadShake();
                break;
            case 3: // 自动识别
                setBgFlash(false);
                setErrorMsg('请正对摄像头，保持光线充足，正在识别...');
                setLoading(true);
                setTimeout(() => {
                    drawMedia();
                }, 800);
                break;
            default:
                break;
        }
    };

    // 计算眼睛纵横比（EAR）
    function getEAR(eye) {
        const a = Math.hypot(eye[1].x - eye[5].x, eye[1].y - eye[5].y);
        const b = Math.hypot(eye[2].x - eye[4].x, eye[2].y - eye[4].y);
        const c = Math.hypot(eye[0].x - eye[3].x, eye[0].y - eye[3].y);
        return (a + b) / (2.0 * c);
    }

    // 计算嘴部纵横比（MAR）
    function getMAR(landmarks) {
        // 62, 66 上下唇中点， 60, 64 左右嘴角
        const top = landmarks.positions[62];
        const bottom = landmarks.positions[66];
        const left = landmarks.positions[60];
        const right = landmarks.positions[64];
        const mar = Math.hypot(top.x - bottom.x, top.y - bottom.y) / Math.hypot(left.x - right.x, left.y - right.y);
        return mar;
    }

    let open = () => {
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        navigator.mediaDevices
            .getUserMedia({
                video: true,
            })
            .then((stream) => {
                video.current.srcObject = stream;
                video.current?.play();
            })
            .catch((err) => {
                console.log('err', err);
                alert('摄像头打开失败');
                setShowModal(false);
            });
    };

    let close = () => {
        if (video.current && video.current.srcObject) {
            const tracks = video.current.srcObject.getTracks();
            tracks.forEach((track) => track.stop());
            video.current.srcObject = null;
        }
    };

    function maskName(name) {
        if (!name) return '';
        if (name.length === 2) return name[0] + '*';
        if (name.length > 2) return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
        return name;
    }

    let drawMedia = async () => {
        console.log('开始人脸识别...');
        const ctx = canvas.current?.getContext('2d');
        if (!ctx) {
            console.error('无法获取canvas上下文');
            setErrorMsg('摄像头初始化失败');
            return;
        }
        
        ctx?.clearRect(0, 0, canvas.current.width, canvas.current.height);
        ctx.drawImage(
            video.current,
            (canvas.current.width - canvas.current.width * (320 / 240)) / 2,
            0,
            canvas.current.width * (320 / 240),
            canvas.current.height,
        );
        const base64 = canvas.current.toDataURL('image/jpeg');
        console.log('图像已捕获，大小:', base64.length);
        try {
            const { data } = await axios.post(`${http}${host}${port}/faceLogin`, {
                base64: base64.split(',')[1],
            });
            if (data.code === '未通过活体检测') {
                setLoading(false);
                setErrorMsg('未通过活体检测，请重新检测');
                setTimeout(() => {
                    setErrorMsg('');
                    setStep(0);
                    detectStep(0);
                }, 1500);
                return;
            }
            if (data.code === -1) {
                setLoading(false);
                setErrorMsg('该人员没有注册');
                setTimeout(() => {
                    setShowModal(false);
                }, 1500);
                return;
            }
            
            // 认证成功
            setLoading(false);
            setSuccess(true);
            setErrorMsg('识别成功！');

            console.log('后端返回数据:', data);

            const userName = data.data?.PersonName || '';
            setRealName(userName);
            localStorage.setItem('realName', userName);

            Toast.show({
                content: `认证成功，欢迎${userName}`,
                duration: 3000,
            });
            setTimeout(() => {
                setShowModal(false);
            }, 2000);
        } catch (e) {
            setLoading(false);
            console.error('人脸识别错误:', e);
            setErrorMsg(`录入失败: ${e.response?.data?.msg || e.message || '未知错误'}`);
            setTimeout(() => {
                setShowModal(false);
            }, 3000);
        }
    };

    // 头像上传处理
    const handleAvatarChange = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = function (evt) {
            const base64 = evt.target.result;
            setUserAvatar(base64);
            localStorage.setItem('userAvatar', base64);
        };
        reader.readAsDataURL(file);
    };

    // 眨眼检测
    const detectBlink = async () => {
        if (!video.current) return;
        
        // 初始化基准眼睛纵横比集合
        if (baseEARArr.current.length === 0) {
            const interval = setInterval(async () => {
                const detections = await faceapi.detectSingleFace(
                    video.current,
                    new faceapi.TinyFaceDetectorOptions()
                ).withFaceLandmarks();
                
                if (detections) {
                    const leftEye = detections.landmarks.getLeftEye();
                    const rightEye = detections.landmarks.getRightEye();
                    const leftEAR = getEAR(leftEye);
                    const rightEAR = getEAR(rightEye);
                    const avgEAR = (leftEAR + rightEAR) / 2.0;
                    
                    baseEARArr.current.push(avgEAR);
                    if (baseEARArr.current.length >= 10) {
                        clearInterval(interval);
                        // 计算基准眼睛纵横比
                        baseEAR.current = baseEARArr.current.reduce((acc, val) => acc + val, 0) / baseEARArr.current.length;
                        console.log('基准眼睛纵横比:', baseEAR.current);
                        startBlinkDetection();
                    }
                }
            }, 100);
        } else {
            startBlinkDetection();
        }
    };
    
    // 开始眨眼检测
    const startBlinkDetection = () => {
        let isEyeClosed = false;
        let lastBlinkTime = Date.now();
        let failedDetections = 0;
        
        // 在界面上显示更新
        setErrorMsg('请看着屏幕并缓慢眨眨眼...');
        
        const interval = setInterval(async () => {
            try {
                const detections = await faceapi.detectSingleFace(
                    video.current,
                    new faceapi.TinyFaceDetectorOptions()
                ).withFaceLandmarks();
                
                if (detections) {
                    failedDetections = 0; // 重置失败计数
                    
                    const leftEye = detections.landmarks.getLeftEye();
                    const rightEye = detections.landmarks.getRightEye();
                    const leftEAR = getEAR(leftEye);
                    const rightEAR = getEAR(rightEye);
                    const avgEAR = (leftEAR + rightEAR) / 2.0;
                    
                    // 放宽眨眼阈值 - 从基准值的85%改为90%，更容易触发
                    const blinkThreshold = baseEAR.current * 0.9; 
                    
                    if (!isEyeClosed && avgEAR < blinkThreshold) {
                        isEyeClosed = true;
                        console.log('眼睛闭上了', avgEAR);
                        setErrorMsg('检测到眨眼...');
                    } else if (isEyeClosed && avgEAR > blinkThreshold) {
                        isEyeClosed = false;
                        console.log('眼睛张开了', avgEAR);
                        
                        // 有效眨眼间隔必须大于200毫秒(更短了)
                        const now = Date.now();
                        if (now - lastBlinkTime > 200) {
                            lastBlinkTime = now;
                            blinkCount.current += 1;
                            console.log('眨眼次数:', blinkCount.current);
                            setErrorMsg(`已检测到${blinkCount.current}次眨眼，需要2次`);
                            
                            // 减少所需次数 - 只需要1次眨眼
                            if (blinkCount.current >= 1) {
                                clearInterval(interval);
                                setErrorMsg('眨眼检测成功！');
                                setTimeout(() => {
                                    setStep(1); // 进入张嘴检测
                                    detectStep(1);
                                }, 800);
                            }
                        }
                    }
                } else {
                    // 检测失败次数增加
                    failedDetections++;
                    if (failedDetections > 10) {
                        setErrorMsg('无法检测到人脸，请保持正面朝向摄像头');
                    }
                }
            } catch (error) {
                console.error('眨眼检测错误:', error);
            }
        }, 100);
        
        // 设置超时，如果8秒内没有检测到眨眼，则自动进入下一步
        setTimeout(() => {
            clearInterval(interval);
            if (blinkCount.current < 1) {
                setErrorMsg('眨眼检测超时，自动进入下一步');
                setTimeout(() => {
                    setStep(1); // 进入张嘴检测
                    detectStep(1);
                }, 800);
            }
        }, 8000); // 减少到8秒
    };
    
    // 张嘴检测
    const detectMouth = async () => {
        let baseMar = null;
        let mouthOpenCount = 0;
        let isMouthOpen = false;
        const startTime = Date.now();
        let failedDetections = 0;
        let samples = [];
        
        // 更新UI提示
        setErrorMsg('请缓慢张嘴再闭上...');
        
        // 首先收集几个样本以获得更稳定的基准值
        const collectSamples = async () => {
            return new Promise((resolve) => {
                let sampleCount = 0;
                const sampleInterval = setInterval(async () => {
                    try {
                        const detections = await faceapi.detectSingleFace(
                            video.current,
                            new faceapi.TinyFaceDetectorOptions()
                        ).withFaceLandmarks();
                        
                        if (detections) {
                            const mar = getMAR(detections.landmarks);
                            samples.push(mar);
                            sampleCount++;
                            
                            if (sampleCount >= 5) {
                                clearInterval(sampleInterval);
                                // 计算中位数而不是平均值，以排除异常值
                                samples.sort((a, b) => a - b);
                                resolve(samples[Math.floor(samples.length / 2)]);
                            }
                        }
                    } catch (error) {
                        console.error('采样错误:', error);
                    }
                }, 200);
                
                // 如果3秒内没有收集到足够样本，使用已收集的样本
                setTimeout(() => {
                    if (samples.length > 0) {
                        clearInterval(sampleInterval);
                        samples.sort((a, b) => a - b);
                        resolve(samples[Math.floor(samples.length / 2)]);
                    } else {
                        // 没有样本，使用一个默认值
                        resolve(0.5);
                    }
                }, 3000);
            });
        };
        
        // 先收集样本
        baseMar = await collectSamples();
        console.log('基准嘴部纵横比(中位数):', baseMar);
        setErrorMsg('准备好了，请张大嘴巴...');
        
        const interval = setInterval(async () => {
            try {
                const detections = await faceapi.detectSingleFace(
                    video.current,
                    new faceapi.TinyFaceDetectorOptions()
                ).withFaceLandmarks();
                
                if (detections) {
                    failedDetections = 0;
                    const mar = getMAR(detections.landmarks);
                    
                    // 降低张嘴阈值，使其更容易触发
                    const mouthThreshold = baseMar * 1.3; // 从1.5降到1.3
                    
                    if (!isMouthOpen && mar > mouthThreshold) {
                        isMouthOpen = true;
                        console.log('嘴巴张开了', mar);
                        setErrorMsg('检测到张嘴，请闭上嘴巴完成动作');
                    } else if (isMouthOpen && mar < mouthThreshold) {
                        isMouthOpen = false;
                        console.log('嘴巴闭上了', mar);
                        mouthOpenCount += 1;
                        
                        // 检测到一次完整的张嘴闭嘴，立即进入下一步
                        clearInterval(interval);
                        setErrorMsg('张嘴检测成功！');
                        setTimeout(() => {
                            setStep(2); // 进入摇头检测
                            detectStep(2);
                        }, 800);
                    }
                } else {
                    // 检测失败计数
                    failedDetections++;
                    if (failedDetections > 10) {
                        setErrorMsg('无法检测到人脸，请保持正面朝向摄像头');
                    }
                }
                
                // 设置超时，如果6秒内没有检测到张嘴，则自动进入下一步
                if (Date.now() - startTime > 6000) {
                    clearInterval(interval);
                    setErrorMsg('张嘴检测超时，自动进入下一步');
                    setTimeout(() => {
                        setStep(2); // 进入摇头检测
                        detectStep(2);
                    }, 800);
                }
            } catch (error) {
                console.error('张嘴检测错误:', error);
            }
        }, 100);
    };
    
    // 摇头检测
    const detectHeadShake = async () => {
        let baseNoseX = null;
        let nosePositions = []; // 存储鼻子位置的数组
        let headShakeCount = 0;
        let isHeadLeft = false;
        let isHeadRight = false;
        const startTime = Date.now();
        let failedDetections = 0;
        let lastDetectionTime = Date.now();
        
        // 更新UI提示
        setErrorMsg('请左右轻微摇头...');
        
        // 收集多个基准样本来计算平均值
        const collectBaseSamples = async () => {
            return new Promise((resolve) => {
                let samples = [];
                const sampleInterval = setInterval(async () => {
                    try {
                        const detections = await faceapi.detectSingleFace(
                            video.current, 
                            new faceapi.TinyFaceDetectorOptions()
                        ).withFaceLandmarks();
                        
                        if (detections) {
                            const nose = detections.landmarks.getNose()[0];
                            samples.push(nose.x);
                            
                            if (samples.length >= 5) {
                                clearInterval(sampleInterval);
                                // 计算平均值
                                const avg = samples.reduce((sum, val) => sum + val, 0) / samples.length;
                                resolve(avg);
                            }
                        }
                    } catch (error) {
                        console.error('收集鼻尖样本错误:', error);
                    }
                }, 200);
                
                // 如果2秒内没收集够样本，就用已有的
                setTimeout(() => {
                    clearInterval(sampleInterval);
                    if (samples.length > 0) {
                        const avg = samples.reduce((sum, val) => sum + val, 0) / samples.length;
                        resolve(avg);
                    } else {
                        // 如果没有样本，用视频宽度的一半作为默认值
                        resolve(video.current ? video.current.videoWidth / 2 : 200);
                    }
                }, 2000);
            });
        };
        
        // 先收集基准样本
        baseNoseX = await collectBaseSamples();
        console.log('基准鼻尖X坐标(平均):', baseNoseX);
        setErrorMsg('请向左右各摇一下头...');
        
        const interval = setInterval(async () => {
            try {
                const now = Date.now();
                // 控制检测频率，防止频繁调用导致性能问题
                if (now - lastDetectionTime < 50) return;
                lastDetectionTime = now;
                
                const detections = await faceapi.detectSingleFace(
                    video.current,
                    new faceapi.TinyFaceDetectorOptions()
                ).withFaceLandmarks();
                
                if (detections) {
                    failedDetections = 0;
                    const nose = detections.landmarks.getNose()[0]; // 鼻尖位置
                    
                    // 存储位置用于绘制轨迹
                    nosePositions.push({x: nose.x, y: nose.y, time: Date.now()});
                    // 只保留最近2秒的位置
                    nosePositions = nosePositions.filter(p => now - p.time < 2000);
                    
                    // 降低摇头阈值，使其更容易触发
                    const shakeThreshold = 15; // 从20降低到15
                    
                    // 检测左右摇头
                    if (!isHeadLeft && nose.x < baseNoseX - shakeThreshold) {
                        isHeadLeft = true;
                        console.log('头向左偏了', nose.x);
                        setErrorMsg('检测到向左摇头，请向右摇...');
                    } else if (!isHeadRight && nose.x > baseNoseX + shakeThreshold) {
                        isHeadRight = true;
                        console.log('头向右偏了', nose.x);
                        setErrorMsg('检测到向右摇头，请向左摇...');
                    }
                    
                    // 如果已经左右都检测到了，就算完成一次摇头
                    if (isHeadLeft && isHeadRight) {
                        headShakeCount += 1;
                        console.log('完成一次摇头', headShakeCount);
                        isHeadLeft = false;
                        isHeadRight = false;
                        
                        // 摇头检测成功，进入下一步
                        clearInterval(interval);
                        setErrorMsg('摇头检测成功！');
                        setTimeout(() => {
                            setStep(3); // 进入最终人脸识别
                            detectStep(3);
                        }, 800);
                    }
                } else {
                    // 检测失败计数
                    failedDetections++;
                    if (failedDetections > 10) {
                        setErrorMsg('无法检测到人脸，请保持正面朝向摄像头');
                    }
                }
                
                // 设置超时，如果6秒内没有检测到摇头，则自动进入下一步
                if (Date.now() - startTime > 6000) {
                    clearInterval(interval);
                    setErrorMsg('摇头检测超时，自动进入下一步');
                    setTimeout(() => {
                        setStep(3); // 进入最终人脸识别
                        detectStep(3);
                    }, 800);
                }
            } catch (error) {
                console.error('摇头检测错误:', error);
            }
        }, 100);
    };
    

// 获取页面文字信息的方法
function getPageText() {
    // 获取页面展示的信息
    let info = '';
    info += `昵称：${user || '未设置'}\n`;
    info += `签名：${qianming || '未设置'}\n`;
    info += `邮箱：${email || '未绑定'}\n`;
    info += `真实姓名：${realName ? maskName(realName) : '未认证'}\n`;
    return info;
}
    return (
        <div className={styles.container}>
            <NavBar onBack={back}>个人资料</NavBar>

            {/* 隐藏的文件选择框 */}
            <input
                type="file"
                accept="image/*"
                ref={fileInputRef}
                style={{ display: 'none' }}
                onChange={handleAvatarChange}
            />

            {/* 第一组 */}
            <div className={styles.group}>
                <List>
                    <List.Item
                        onClick={() => { fileInputRef.current && fileInputRef.current.click(); }}
                        extra={
                            <img 
                                src={userAvatar} 
                                alt="avatar" 
                                className={styles.avatar}
                                onError={(e) => {
                                    e.target.src = "";
                                }}
                            />
                        }
                    >头像</List.Item>
                    <List.Item
                        onClick={() => { navigate('/changename') }}
                        extra={<span className={styles.nickname}>{username || '给自己起个名字吧'}</span>}
                    >昵称</List.Item>
                    <List.Item
                        onClick={() => { navigate('/changeqm')}}
                        extra={<span className={styles.qianming}>{qianming || '这个人很懒，什么都没写~'}</span>}
                    >个性签名</List.Item>
                    <List.Item
                        onClick={() => {
                            setInputEmail(email || '');
                            setEmailError('');
                            setShowEmailModal(true);
                        }}
                        extra={<span className={styles.email}>
                            {email ?
                                email.replace(
                                    /^(\d)(\d+)(\d)@qq\.com$/,
                                    (match, p1, p2, p3) => `${p1}${'*'.repeat(p2.length)}${p3}@qq.com`
                                )
                                : '未绑定'
                            }
                        </span>}
                    >邮箱</List.Item>
                    <List.Item
                        onClick={() => { }}
                        extra={<span className={styles.realName}>{realName ? maskName(realName) : '未认证'}</span>}
                    >真实姓名</List.Item>
                </List>
            </div>

            {/* 第二组 */}
            <div className={styles.group}>
                <List>
                    <List.Item onClick={() => { }}>工作经历</List.Item>
                    <List.Item onClick={() => { }}>教育经历</List.Item>
                    <List.Item
                        onClick={() => {
                            if (realName) {
                                Toast.show({
                                    content: '已录入个人认证，如需修改，请先进行邮箱绑定',
                                    duration: 3000,
                                });
                            } else {
                                setShowModal(true);
                            }
                        }}
                    >个人认证</List.Item>
                </List>
            </div>

            {/* 第三组 */}
            <div className={styles.group}>
                <List>
                    <List.Item onClick={() => {setShowQRModal(!showQRModal);  }}>我的二维码</List.Item>
                </List>
            </div>

            {/* 圆形弹框 */}
            {showModal && (
                <div className={styles.modalOverlay}>
                    <div className={`${styles.modalContent} ${bgFlash ? styles.flashBg : ''}`}>
                        <video
                            ref={video}
                            preload="auto"
                            autoPlay
                            loop
                            muted
                            width="360"
                            height="360"
                            className={styles.video}
                        ></video>
                        <canvas ref={canvas} width="400" height="400" className={styles.hiddenCanvas}></canvas>
                        <div className={styles.modalMessage}>
                            {loading ? '正在识别...' : errorMsg}
                        </div>
                        {/* 显示当前步骤 */}
                        <div className={styles.modalStep}>
                            {step === 0 && '步骤1/3: 眨眼检测'}
                            {step === 1 && '步骤2/3: 张嘴检测'}
                            {step === 2 && '步骤3/3: 摇头检测'}
                            {step === 3 && '正在验证身份...'}
                        </div>
                        <button
                            className={styles.closeButton}
                            onMouseOver={e => e.currentTarget.style.background = 'rgba(0,0,0,0.18)'}
                            onMouseOut={e => e.currentTarget.style.background = 'rgba(0,0,0,0.08)'}
                            onClick={() => setShowModal(false)}
                        >×</button>
                    </div>
                </div>
            )}

            {/* 邮箱输入弹框 */}
            {showEmailModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <div className={styles.modalTitle}>请输入邮箱</div>
                        <input
                            type="email"
                            value={inputEmail}
                            onChange={e => {
                                setInputEmail(e.target.value);
                                setEmailError('');
                            }}
                            placeholder="请输入邮箱"
                            className={styles.modalInput}
                        />
                        {emailError && <div className={styles.errorMessage}>{emailError}</div>}
                        <div className={styles.modalButtons}>
                            <button
                                className={styles.modalCancelButton}
                                onClick={() => setShowEmailModal(false)}
                            >取消</button>
                            <button
                                className={styles.modalConfirmButton}
                                onClick={() => {
                                    // 邮箱格式校验
                                    const emailReg = /^[a-zA-Z0-9_.+-]+@qq\.com$/;
                                    if (!inputEmail) {
                                        setEmailError('邮箱不能为空');
                                        return;
                                    }
                                    if (!emailReg.test(inputEmail)) {
                                        setEmailError('请输入有效的QQ邮箱');
                                        return;
                                    }
                                    setShowEmailModal(false);
                                    setShowSlider(true);
                                }}
                            >确定</button>
                        </div>
                        <button
                            className={styles.closeButton}
                            onClick={() => setShowEmailModal(false)}
                        >×</button>
                    </div>
                </div>
            )}

            {/* 滑块弹窗 */}
            {showSlider && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <div className={styles.modalTitle}>请完成滑块验证</div>
                        <SliderCaptcha
                            request={async () => ({
                                bgUrl: '/dt.jpg',
                                puzzleUrl: '/xt.png',
                            })}
                            onVerify={async (data) => {
                                // 简单模拟滑块验证通过
                                setShowSlider(false);
                                // 发送验证码
                                try {
                                    const res = await axios.post(`${http}${host}${port}/send-qq-code`, { email: inputEmail });
                                    if (res.data.code === 0) {
                                        setShowCodeModal(true);
                                        Toast.show({ content: '验证码已发送到邮箱', duration: 2000 });
                                    } else {
                                        Toast.show({ content: res.data.msg || '验证码发送失败', duration: 2000 });
                                    }
                                } catch (err) {
                                    console.error('发送验证码错误:', err);
                                    Toast.show({ content: '验证码发送失败，请检查网络连接', duration: 2000 });
                                }
                            }}
                        />
                        <button
                            className={styles.closeButton}
                            onClick={() => setShowSlider(false)}
                        >×</button>
                    </div>
                </div>
            )}

            {/* 验证码输入弹框 */}
            {showCodeModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <div className={styles.modalTitle}>请输入验证码</div>
                        <input
                            type="text"
                            value={inputCode}
                            onChange={e => {
                                setInputCode(e.target.value);
                                setCodeError('');
                            }}
                            placeholder="请输入邮箱收到的验证码"
                            className={styles.modalInput}
                        />
                        {codeError && <div className={styles.errorMessage}>{codeError}</div>}
                        <div className={styles.modalButtons}>
                            <button
                                className={styles.modalCancelButton}
                                onClick={() => setShowCodeModal(false)}
                            >取消</button>
                            <button
                                className={styles.modalConfirmButton}
                                onClick={async () => {
                                    if (!inputCode) {
                                        setCodeError('验证码不能为空');
                                        return;
                                    }
                                    try {
                                        const username = localStorage.getItem('username');
                                        const res = await axios.post(`${http}${host}${port}/verify-qq-code`, { 
                                            email: inputEmail, 
                                            code: inputCode,
                                            username: username
                                        });
                                        if (res.data.code === 0) {
                                            setShowCodeModal(false);
                                            setEmail(inputEmail);
                                            localStorage.setItem('userEmail', inputEmail);
                                            Toast.show({ content: '邮箱验证成功', duration: 2000 });
                                        } else {
                                            setCodeError(res.data.msg || '验证码错误');
                                        }
                                    } catch (err) {
                                        console.error('邮箱验证错误:', err);
                                        setCodeError('验证码验证失败，请检查网络连接');
                                    }
                                }}
                            >确定</button>
                        </div>
                        <button
                            className={styles.closeButton}
                            onClick={() => setShowCodeModal(false)}
                        >×</button>
                    </div>
                </div>
            )}
{showQRModal && (
    <div className={styles.modalOverlay}>
        <div className={styles.modalContent}>
            <div className={styles.modalTitle}>我的二维码</div>
            <QRCodeSVG value={getPageText()} size={200} />
            <button
                className={styles.closeButton}
                onClick={() => setShowQRModal(!showQRModal)}
            >×</button>
        </div>
    </div>
)}
        </div>
    )
}


export default Renlian;